package com.siso.edu.instrument.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.siso.edu.instrument.bean.RecordDataEntity;
import com.siso.edu.instrument.dialog.BluetoothConnectingDialog;
import com.siso.edu.instrument.fragment.BottomFragment;
import com.siso.edu.instrument.util.FileUtil;
import com.siso.edu.instrument.util.SDCardUtil;
import com.siso.edu.instrument.util.XmlFileUtil;
import com.transcom.measstatemachine.MeasStateMachine;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * 保存数据、手机蓝牙经纬度数据
 */
public class BlueToothDataActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "BlueToothDataActivity";
    EditText etAddressCode;
    EditText etCarCode;
    EditText etBeginHz;
    EditText etEndHz;
    EditText etStepLength;
    EditText etMethod;
    EditText etMark;
    EditText etRecordHead;
    EditText etDeviceInfo;
    EditText etHeight;
    Spinner spinner_jihua;
    Spinner spinner_mark;

    Spinner spinner_device;//设备参数
    Spinner spinner_info;//天线信息
    String fileName;
    String filePath;
    String part1Address;
    String part2Car;
    String part3Date;
    String part4Time;
    String part5Begin;
    String part6End;
    String part7Step;
    String part8Method;
    String part9Mark;

    Button btnSave;

    int recordHead;
    short carCode;
    byte deviceInfo;//
    int device;//设备参数
    int info;//天线信息
    short year;
    byte mouth;
    byte day;
    byte hour;
    byte minute;
    byte second;
    short miniSecond;
    double latitude;//维度
    double longitude;//经度
    int height;

    long beginHz;
    int step;
    static final int hzPoint = 1023;
    double[] testData = new double[1023];
    //
    private static final int REFRESH_OPEN = 1;
    private static final int REFRESH_LOCATION = 2;

    //控制蓝牙开关
    boolean isBTOpen;
    private TextView mTvlongitude, mTvLatitude, count;
    private Button btnRead, btnStartService;
    private Switch aSwitch;
    //蓝牙服务模块
    private BluetoothServerSocket mServerSocket;
    //蓝牙通信模块
    private BluetoothSocket mSocket;
    //蓝牙适配器
    private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    //服务器名称
    public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";
    private static final int STATUS_CONNECT = 0x11;//连接成功
    private static final int STATUS_START_SERVICE = 0x12;//开启服务
    private Timer timer = new Timer();
    private Button btn_local_test;//测试数据

    private EditText et_time_length;// 保存时间间隔

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_data_tooth);
        initView();
        initData();
        setFilename();
        init();
        //用来接收经纬度并且判断是否更新
        data[0] = 0;
        data[1] = 0;
        //用来使其可以在3600秒内可以被其他设备搜索到，并且打开蓝牙
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);
        startActivity(discoverableIntent);
        onclick();

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.button_s:   //开启服务器线程，本机作为服务器端，而手机作为客户端进行数据发送
                closeConnction();
                serverThread = new ServerThread();
                serverThread.start();
                break;
            case R.id.button:    //读取发送过来的位置信息，开启读取线程
                mReadThread = new readThread();
                mReadThread.start();
                break;
            case R.id.btn_save:
//                mSaveData = new BluetoothConnectingDialog(BlueToothDataActivity.this, getResources().getString(R.string.blue_save_data));
//                mSaveData.show();
                //保存1023数据对应的配置信息
                File file = new File(Environment.getExternalStorageDirectory() + File.separator + getString(R.string.spectrum_analyzer_directory_name) +
                        File.separator + BottomFragment.BlueToothData, BottomFragment.CurrentSpectrum);
                if (file.exists()) {
                    file.delete();
                }
                XmlFileUtil.writeXmlFile(Environment.getExternalStorageDirectory() + File.separator + getString(R.string.spectrum_analyzer_directory_name) +
                        File.separator + BottomFragment.BlueToothData, BottomFragment.CurrentSpectrum, MainActivity.getCurrentSpectrum());

                int timeLength = 5 * 1000;// 保存时间间隔
                try {
                    timeLength = Integer.parseInt(et_time_length.getText().toString()) * 1000;
                } catch (Exception e) {
                    timeLength = 5 * 1000;
                }
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        boolean sdCarsSize = SDCardUtil.sdCardSize200M(BlueToothDataActivity.this);
                        Log.e(TAG, "saveData: " + FileUtil.getAutoFileOrFilesSize(filePath + fileName));
                        Log.e(TAG, "saveData: " + FileUtil.getFileOrFilesSize(filePath + fileName, FileUtil.SIZETYPE_MB));
                        if (sdCarsSize) {
                            if (FileUtil.getFileOrFilesSize(filePath + fileName, FileUtil.SIZETYPE_MB) < 200) {
                                saveData();
                            } else {
                                initData();
                                setFilename();
                                saveData();
                            }
                        } else {
                            timer.cancel();
                            Toast.makeText(BlueToothDataActivity.this, "存储空间不足", Toast.LENGTH_LONG).show();
                            return;
                        }


                    }
                }, 1000, timeLength);
                break;
            default:
                break;

        }

    }

    private void onclick() {
        btnRead.setOnClickListener(this);
        btnStartService.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Open();
                } else {
                }
            }
        });


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null)
            timer.cancel();
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
            mBtAdapter = null;
        }
        closeConnction();
    }

    private void closeConnction() {
        if (mSocket != null) {
            try {
                mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mServerSocket != null) {
            try {
                mServerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 计算设备参数与天线信息
     *
     * @param device
     * @param info
     * @return
     */
    private int calcDeviceInfo(int device, int info) {
        int deviceinfo = 0;
        if (device == 0) {
            device = info;
        } else if (device == 1) {
            deviceinfo = 16 + info;

        }
        return deviceinfo;
    }

    public void saveData() {
        content = "";
        //TODO
        recordHead = 0;
        carCode = Short.parseShort(part2Car);
        deviceInfo = (byte) calcDeviceInfo(device, info);
        Calendar calendar = Calendar.getInstance();
        if (mLocation != null) {
            calendar.setTimeInMillis(mLocation.getTime());
        }
        year = (short) calendar.get(Calendar.YEAR);
        mouth = (byte) (calendar.get(Calendar.MONTH) + 1);
        day = (byte) calendar.get(Calendar.DAY_OF_MONTH);
        hour = (byte) calendar.get(Calendar.HOUR_OF_DAY);
        minute = (byte) calendar.get(Calendar.MINUTE);
        second = (byte) calendar.get(Calendar.SECOND);
        miniSecond = (short) calendar.get(Calendar.MILLISECOND);
        if (mLocation != null) {
            latitude = mLocation.getLatitude();
            longitude = mLocation.getLongitude();
            height = (int) mLocation.getAltitude();
        }
        beginHz = (long) MainActivity.getCurrentSpectrum().getStartFrequency();
        step = (int) ((MainActivity.getCurrentSpectrum().getStopFrequency() - MainActivity.getCurrentSpectrum().getStartFrequency()) / (1023 - 1));
        for (int j = 0; j < MeasStateMachine.saveData.length; j++) {
            //1023
//            testData[j] = PowerConvertUtil.DbmToDbuv(Double.parseDouble(DecimalUtil.dataFormate(MeasStateMachine.saveData[j], "#.#")), 50.0);
            testData[j] = MeasStateMachine.saveData[j];
        }
        contextStr();
        RecordDataEntity entity = new RecordDataEntity();
        entity.setCarCode(carCode);
        entity.setDeviceInfo(deviceInfo);
        entity.setYear(year);
        entity.setMouth(mouth);
        entity.setDay(day);
        entity.setHour(hour);
        entity.setMinute(minute);
        entity.setSecond(second);
        entity.setMiniSecond(miniSecond);
        entity.setLongitude(longitude);
        entity.setLatitude(latitude);
        entity.setHeight(height);
        entity.setBeginHz(beginHz);
        entity.setStep(step);
        entity.setHzPoint(hzPoint);
        entity.setTestData(testData);
        try {
            FileUtil.writeBinary(entity, filePath, fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 字符串保存
     */
    private void contextStr() {
        StringBuilder sb = new StringBuilder();
        sb.append(recordHead);
        sb.append(",");
        sb.append(carCode);
        sb.append(",");
        sb.append(deviceInfo);
        sb.append(",");
        sb.append(year);
        sb.append(",");
        sb.append(mouth);
        sb.append(",");
        sb.append(day);
        sb.append(",");
        sb.append(hour);
        sb.append(",");
        sb.append(minute);
        sb.append(",");
        sb.append(second);
        sb.append(",");
        sb.append(miniSecond);
        sb.append(",");
        sb.append(latitude);
        sb.append(",");
        sb.append(longitude);
        sb.append(",");
        sb.append(height);
        sb.append(",");
        sb.append(beginHz);
        sb.append(",");
        sb.append(part6End);
        sb.append(",");
        sb.append(step);
        sb.append(",");
        sb.append(hzPoint);
        sb.append(",");
        for (int i = 0; i < testData.length; i++) {
            sb.append(testData[i]);
            sb.append(",");
        }

        sb.append("\r\n");
        content = sb.toString();
        try {
            FileUtil.writeData(content, filePath, "123.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String content;

    private void setFilename() {
        filePath = Environment.getExternalStorageDirectory() + File.separator + "SpecAn" + File.separator + "BlueToothData" + File.separator;
        fileName = part1Address + "_" + part2Car + "_" + part3Date + "_" + part4Time + "_" + part5Begin + "_" + part6End + "_" + part7Step + "_" + part8Method + "_" + part9Mark + ".bin";

    }


    private void initData() {
        part1Address = etAddressCode.getText().toString();
        part2Car = etCarCode.getText().toString();
        part3Date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        part4Time = new SimpleDateFormat("HHmmss").format(new Date());
//        part5Begin = etBeginHz.getText().toString();
//        part6End = etEndHz.getText().toString();
        part5Begin = String.valueOf(MainActivity.getCurrentSpectrum().getStartFrequency());
        part6End = String.valueOf(MainActivity.getCurrentSpectrum().getStopFrequency());
        part7Step = etStepLength.getText().toString();
        part8Method = etMethod.getText().toString();
        part9Mark = etMark.getText().toString();
    }

    private void initView() {
        etAddressCode = (EditText) findViewById(R.id.et_address_code);
        etCarCode = (EditText) findViewById(R.id.et_car_code);
        etBeginHz = (EditText) findViewById(R.id.et_begin_hz);
        etEndHz = (EditText) findViewById(R.id.et_end_hz);
        etStepLength = (EditText) findViewById(R.id.et_step_length);
        etMethod = (EditText) findViewById(R.id.et_method);
        etMark = (EditText) findViewById(R.id.et_mark);
        btnSave = (Button) findViewById(R.id.btn_save);
        etRecordHead = (EditText) findViewById(R.id.et_record_head);
        etDeviceInfo = (EditText) findViewById(R.id.et_device_info);
        etHeight = (EditText) findViewById(R.id.et_height);

        spinner_jihua = (Spinner) findViewById(R.id.spinner_jihua);
        spinner_mark = (Spinner) findViewById(R.id.spinner_mark);
        spinner_device = (Spinner) findViewById(R.id.spinner_device);
        spinner_info = (Spinner) findViewById(R.id.spinner_info);
        et_time_length = (EditText) findViewById(R.id.et_time_length);

        //极化方式
        spinner_jihua.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] jihua = getResources().getStringArray(R.array.jihua);
                part8Method = jihua[position];

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //标志
        spinner_mark.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] mark = getResources().getStringArray(R.array.mark);
                part9Mark = mark[position];

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //设备参数
        spinner_device.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] d = getResources().getStringArray(R.array.device);
                device = Integer.parseInt(d[position]);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //天线信息
        spinner_info.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] i = getResources().getStringArray(R.array.info);
                info = Integer.parseInt(i[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //测试
        btn_local_test = (Button) findViewById(R.id.btn_local_test);
        btn_local_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String path = Environment.getExternalStorageDirectory() + File.separator + "SpecAn" + File.separator + "BlueToothData" + File.separator;
                String name = null;
                List<String> list = FileUtil.getFileName(path);
                for (String s : list) {
                    if (s.endsWith(".bin")) {
                        name = s;
                    }
                }
                try {
                    List<RecordDataEntity> recordEntityList = FileUtil.readBinData(path, name);
                    localData_1023 = recordEntityList.get(0).getTestData();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private static double[] localData_1023 = new double[1023];
    ServerThread serverThread;

    // 开启服务器,服务器端线程
    private class ServerThread extends Thread {
        public void run() {
            try {
                // 创建一个蓝牙服务器 参数分别：服务器名称、UUID
                mServerSocket = mBtAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,
                        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

                Message msg = new Message();
                msg.obj = "请稍候，正在等待客户端的连接...";
                Log.e(TAG, "run: " + msg.obj);
                msg.what = STATUS_START_SERVICE;
                mHandler.sendMessage(msg);
                /* 接受客户端的连接请求 */
                mSocket = mServerSocket.accept();
                msg = new Message();
                msg.obj = "客户端已经连接上";
                Log.e(TAG, "run: " + msg.obj);
                msg.what = STATUS_CONNECT;
                mHandler.sendMessage(msg);
                // 启动接受数据
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
    }

    private readThread mReadThread;

    //读取消息线程，
    private class readThread extends Thread {

        public void run() {
            byte[] buffer = new byte[1024];//流的缓冲大小
            int bytes;//用于保存read所读取的字节数
            InputStream in = null;//输入流赋值为空
            while (true) {
                try {
                    Log.e(TAG, "连接状态: " + mSocket.isConnected());
                    in = mSocket.getInputStream();//从socket中获取输入流
                    if ((bytes = in.read(buffer)) > 0) {//从输入流中读取数据，若输入流中有数据才会执行，若没有则不执行
                        byte[] buf = new byte[bytes];
                        for (int i = 0; i < bytes; i++) {
                            buf[i] = buffer[i];
                        }
                        String data = new String(buf);
                        Message msg = Message.obtain();
                        msg.what = REFRESH_LOCATION;
                        msg.obj = data;
                        mHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Exception: 接受数据错误");
//                    try {
//                        in.close();
//                    } catch (Exception e2) {
//                    }
                    break;
                }
            }
        }

    }

    //打开蓝牙
    private void Open() {
        isBTOpen = mBtAdapter.isEnabled();//蓝牙是否打开
        if (!isBTOpen) {
            boolean open = mBtAdapter.enable();//如果没打开，则打开
            if (open) {
                Toast.makeText(BlueToothDataActivity.this, "蓝牙已经打开",
                        Toast.LENGTH_SHORT).show();//成功打开蓝牙后提示打开
            } else {
                Toast.makeText(BlueToothDataActivity.this,
                        "蓝牙无法打开", Toast.LENGTH_SHORT).show();//失败后提示无法打开
            }
        } else {
            boolean close = mBtAdapter.disable();//关闭蓝牙
            if (close) {
                Toast.makeText(BlueToothDataActivity.this, "关闭蓝牙",
                        Toast.LENGTH_SHORT).show();//成功关闭后提示
            } else {
                Toast.makeText(BlueToothDataActivity.this,
                        "蓝牙已经关闭", Toast.LENGTH_SHORT)//无法关闭后提示
                        .show();
            }
        }
        Message msg = Message.obtain();
        msg.what = REFRESH_OPEN;
        mHandler.sendMessageDelayed(msg, 1000);
    }

    //处理打开蓝牙函数中发过来的消息
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            String info = (String) msg.obj;
            switch (msg.what) {
                case REFRESH_OPEN:
                    isBTOpen = mBtAdapter.isEnabled();//表示是否打开
                    if (isBTOpen) {
                        Toast.makeText(BlueToothDataActivity.this, "蓝牙已经打开", Toast.LENGTH_SHORT).show();//
                    } else {
                        Toast.makeText(BlueToothDataActivity.this, "蓝牙已经关闭", Toast.LENGTH_SHORT).show();//
                    }
                    break;
                case STATUS_START_SERVICE:
                    //开始连接中。。。
                    Toast.makeText(BlueToothDataActivity.this, info, Toast.LENGTH_LONG).show();
                    mBluetoothConnectingDialog = new BluetoothConnectingDialog(BlueToothDataActivity.this, getResources().getString(R.string.blue_connectiong));
                    mBluetoothConnectingDialog.show();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            mBluetoothConnectingDialog.dismiss();
                        }
                    }, 5000);
                    break;
                case STATUS_CONNECT:
                    //连接成功
                    mBluetoothConnectingDialog.dismiss();
                    Toast.makeText(BlueToothDataActivity.this, info, Toast.LENGTH_LONG).show();
                    //读取发送过来的位置信息，开启读取线程
                    mReadThread = new readThread();
                    mReadThread.start();
                    Log.e(TAG, "handleMessage: STATUS_CONNECT");
                    break;

                case REFRESH_LOCATION:
                    String str1 = (String) msg.obj;
                    Log.e(TAG, "handleMessage: " + str1);
                    String[] strarr = str1.split(";")[0].split(",");
                    double latitude = Double.valueOf(strarr[0]);
                    double longitude = Double.valueOf(strarr[1]);
                    double altitude = Double.valueOf(strarr[2]);
                    long time = Long.parseLong(strarr[3]);
                    if (mLocation == null) {
                        mLocation = new Location("");
                    }
                    if (data[0] == latitude && data[1] == longitude) {

                    } else {
                        data[0] = latitude;
                        data[1] = longitude;
                        gps_count = gps_count + 1;
                        count.setText(String.valueOf(gps_count));
                    }
                    mLocation.setLatitude(latitude);
                    mLocation.setLongitude(longitude);
                    mLocation.setAltitude(altitude);
                    mLocation.setTime(time);
                    updateLocation();
                    break;
            }

            super.handleMessage(msg);
        }
    };
    BluetoothConnectingDialog mBluetoothConnectingDialog;
    BluetoothConnectingDialog mSaveData;
    private int gps_count = 0;
    private double[] data = new double[2];
    private Location mLocation;

    private void updateLocation() {
        String strLongitude;
        String strLatitude;
        if (mLocation != null) {
            strLongitude = "经度:" + String.format("%.7f", mLocation.getLongitude());
            strLatitude = "维度:" + String.format("%.7f", mLocation.getLatitude());
        } else {
            strLongitude = "经度:" + "0";
            strLatitude = "维度:" + "0";
        }
        mTvlongitude.setText(strLongitude);
        mTvLatitude.setText(strLatitude);

    }

    private void init() {
        mTvlongitude = (TextView) findViewById(R.id.jing_du);
        mTvLatitude = (TextView) findViewById(R.id.wei_du);
        aSwitch = (Switch) findViewById(R.id.bt_on_off);
        btnRead = (Button) findViewById(R.id.button);
        btnStartService = (Button) findViewById(R.id.button_s);
        count = (TextView) findViewById(R.id.count);
    }


}
